from db.db import DB
from cache.redis_util import cache


class SpiderPlan:
    name: str
    index: int
    size: int
    status: int

    columns = ["name", "[index]", "size", "status"]

    __slots__ = ["name", "index", "size", "status", "_db", "_func", "_list", "_is_load"]

    def __init__(self, db: DB, name, _list: list, is_load=True):
        self._db = db
        self._func = None
        self._list = _list
        self.index = 0
        self.size = len(_list)
        self.name = name
        self._is_load = is_load

    def init(self):
        self._func = None
        self.index = 0
        self.size = 0

    def load(self, index,size):
        self.index = index
        self.size = size
        if self.index == self.size:
            self.index = 0

    def write(self, status=0):
        pass

    def __iter__(self):
        if self._is_load:
            self.load(self.index, self.size)
        return self

    def __next__(self):
        if self.index >= self.size:
            raise StopIteration()

        @cache(60 * 60, namespace=f"{self.name}:{self.index}")
        def _run():
            return self._list[self.index]
        _data = _run()
        self.index += 1
        return _data
